package com.wzdigit.wms.wms.task;

import com.wzdigit.framework.utils.RedisUtil;
import com.wzdigit.mes.basic.api.BasicDataItemDetailApi;
import com.wzdigit.mes.basic.dto.DataItemDetailDTO;
import com.wzdigit.wms.basic.domain.mid.IfPostback;
import com.wzdigit.wms.basic.enums.writeback.TopicEnum;
import com.wzdigit.wms.wms.service.mid.IfPostbackService;
import com.wzdigit.wms.wms.strategy.webservice.handle.SendWebServiceHandle;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 数据回写-》SAP,OMS 定时任务
 */

@ConditionalOnExpression("${schedule.common.switch}")
@Component
@EnableScheduling
@Slf4j
public class DataReturnSchedule implements SchedulingConfigurer {

    @Value("${schedule.data_return.start_flag}")
    private Boolean startScheduleFlag;

    @Value("${schedule.data_return.frequency}")
    private String cron;

    @Value("${schedule.data_return.pause_state_key}")
    private String pauseStateKey;//暂停标识KEY

    @Autowired
    IfPostbackService ifPostbackService;

    @Autowired
    SendWebServiceHandle sendWebServiceHandle;

    @Reference(version = "${dubbo.consumers.basic.data.item.detail.api:1.0.0}", check = false, timeout = 300000)
    private BasicDataItemDetailApi dataItemDetailApi;

    final Lock lock = new ReentrantLock();

    final Condition condition = lock.newCondition();

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        //根据CRON构建定时任务
        taskRegistrar.addCronTask(() -> {

            lock.lock();
            try {
                DataItemDetailDTO dto = dataItemDetailApi.getDataItemDetailByPCodeAndName("oqc_fp_flag", "key");
                if (dto!=null){
                    if ("0".equals(dto.getItemValue())){
                        return;
                    }
                }
                //定时任务逻辑
                log.info("【数据回写】定时任务执行");
                log.info("【数据回写】定时任务执行");
                //根据各个枚举标识，执行各个逻辑

                //查询数据回传表
                List<IfPostback> ifPostbackList = ifPostbackService.selectSendWebServiceDatas();

                //根据策略开始调SAP ，OMS接口，并回写数据回传表
                for (IfPostback ifPostback : ifPostbackList) {

                    String topic = ifPostback.getPostbackTopic();

                    TopicEnum topicEnum = TopicEnum.getEnumByName(topic);
                    //发送报文请求，并更新【数据回传表】
                    try {
                        Object send = sendWebServiceHandle.send(topicEnum, ifPostback);
                    }catch (Exception e){
                        e.printStackTrace();;
                    }

                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

        }, this.getCron());

    }

    /**
     * 构造CRON表达式
     */
    public String getCron() {

        //若果为TRUE，表示执行定时任务
        if (!startScheduleFlag) {
            //返回不执行定时任务标识
            return ScheduledTaskRegistrar.CRON_DISABLED;
        }

//        lock.lock();
//        try {
//            condition.await();
//        } catch (Exception e) {
//            e.printStackTrace();
//        } finally {
//            lock.unlock();
//        }
        log.info("【数据回写】执行的cron表达式:{}", cron);
        return cron;
    }

    /**
     * 设置定时任务为【运行】标识
     */
    @Deprecated
    public void setTaskRunningState() {

        RedisUtil.set(pauseStateKey, true);//设置暂停标识为TRUE
        condition.signal();
    }

    /**
     * 设置定时任务为【暂停】标识
     */
    @Deprecated
    public void setTaskPauseState() {

        RedisUtil.set(pauseStateKey, false);//设置暂停标识为TRUE
        condition.signal();
    }
}